package info.niwota.group;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class NameIndex {
	private static final String ellipsis = " \u2026 "; //" ..... "

	private static class IndexTask extends AsyncTask<Void, Void, NameIndex[]> {
		private ArrayAdapter<NameIndex> adapter;
		private ContactListAdapter indexed;

		public IndexTask(ContactListAdapter indexed,
				ArrayAdapter<NameIndex> adapter) {
			this.indexed = indexed;
			this.adapter = adapter;
		}

		@Override
		protected NameIndex[] doInBackground(Void... params) {
			final boolean starring = (indexed.getSortBy() == ContactListAdapter.SORT_BY_STAR);
			List<EmailContact> contacts = indexed.getContacts();
			final NameIndex[] indice = build(contacts, PAGESIZE, starring);
			return indice;
		}

		@Override
		protected void onPostExecute(final NameIndex[] indice) {
			if (indice != null) {
				adapter.clear();
				for (int i = 0; i < indice.length; i++) {
					adapter.add(indice[i]);
				}
				adapter.notifyDataSetChanged();
			}
		}
	}
	public static final int PAGESIZE = 6;

	private static final char[] STARS = new char[] { ' ', '*', '#' };
	/**
	 * Balanced indice for a list of contacts ordered by name or by star/name
	 * 
	 * @return
	 */
	private static NameIndex[] build(List<EmailContact> list, int pagesize,
			boolean starring) {
		if (list == null) {
			return null;
		}
		int total = list.size();
		int pages = total / pagesize + (total % pagesize > 0 ? 1 : 0);
		//
		if (pages < 1) {
			return null;
		}
		NameIndex[] indice = new NameIndex[pages];
		for (int i = 0; i < pages; i++) {
			int pos = i * pagesize;
			EmailContact ec = list.get(pos);
			String cur = ec.name;
			String n = (pos == 0 ? cur.substring(0, 1) : diffstr(cur, list
					.get(pos - 1).name));
			//
			NameIndex idx = new NameIndex();
			idx.pos = pos;
			idx.name = (starring ? STARS[ec.getStarred()] : "") + "\t" + n
					+ ellipsis + cur;
			indice[i] = idx;
		}
		return indice;
	}

	private static String diffstr(String cur, String prev) {
		int len1 = cur.length();
		int len2 = prev.length();
		int len = Math.min(len1, len2);
		for (int i = 0; i < len; i++) {
			if (cur.charAt(i) != prev.charAt(i)) {
				return cur.substring(0, i + 1);
			}
		}
		len = Math.min(len1, (len + 1)); // des or asc
		return cur.substring(0, len);
	}

	public static AlertDialog showIndex(final Context context,
			final ContactListAdapter indexed, final ListView view) {
		final AlertDialog.Builder b = new AlertDialog.Builder(context);
		b.setCustomTitle(null);
		final ArrayAdapter<NameIndex> items = new ArrayAdapter<NameIndex>(
				context, R.layout.index_dialog_item);
		b.setAdapter(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				NameIndex i = (NameIndex) items.getItem(which);
				if (i == null) {
					return;
				}
				view.setSelected(false);
				view.setSelection(i.pos);
			}
		});
		final AlertDialog d = b.create();
		d.show();
		//save some time for long list - not proved?
		new IndexTask(indexed, items).execute();
		//
		return d;
	}

	public String name; // shortest name that differs from preceding one
	public int pos; // position in sorted list

	public NameIndex() {
	}

	@Override
	public String toString() {
		return name;
	}
}
